package com.news.listener;


import com.news.service.AdverService;
import com.news.service.impl.AdverServiceImpl;

import javax.servlet.*;
import java.util.HashMap;
import java.util.Map;

/**
 *  监听请求、会话、上下文的生命周期或属性状态
 *  实现步骤：
 *  1.实现XXXListener 或 XXXAttributeListener接口
 *  2.重写 方法
 *  3.配置web.xml 或  @WebListener
 */
public class ApplicationListener implements ServletContextListener, ServletContextAttributeListener {
    private AdverService adverService = new AdverServiceImpl();

    @Override
    public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
        System.out.println("上下文的属性：新增");
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
        System.out.println("上下文的属性：删除");
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
        System.out.println("上下文的属性：替换");
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("上下文初始化完成。。。");
        ServletContext application = servletContextEvent.getServletContext();
        try{
            application.setAttribute("topicList",adverService.getAll());
            System.out.println("新闻主题加载成功。。。");
        }catch(Exception e){
            System.out.println("新闻主题加载失败。。。");
        }
        try{
            application.setAttribute("loginUserMap",new HashMap<>());
            System.out.println("在线用户加载成功loginUserMap。。。");
        }catch(Exception e){
            System.out.println("在线用户集合加载失败。。。");
        }
        try{
            Map<String,String> map = new HashMap<String,String>();
            map.put("你","*");
            map.put("我","*");
            map.put("他","*");
            map.put("<","&lt;");
            map.put(">","&gt;");
            application.setAttribute("textMap",map);
            System.out.println("脏文集合加载成功。。。");
        }catch(Exception e){
            System.out.println("脏文集合加载失败。。。");
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("上下文销毁。。。");
    }
}
